import sys

from loguru import logger
from loguru._defaults import env
from tqsdk import TqApi, TqAccount

import trade.s1 as s1

PROT_LOGURU_FORMAT = env(
    "LOGURU_FORMAT",
    str,
    "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
    "<level>{level: <8}</level> | "
    "{message}",
)

logger.remove(handler_id=None)
logger.add(sys.stdout, level="INFO", format=PROT_LOGURU_FORMAT)
logger.add("c:/logs/prot_s1.log", enqueue=True, rotation='1 MB', retention='10 days', encoding="UTF-8")

# api = TqApi(TqSim(), web_gui="http://0.0.0.0:8081")
# api = TqApi(TqAccount(broker_id="B宝城期货", account_id="821000319", password="Ff041002"), web_gui="http://0.0.0.0:8081")
api = TqApi(TqAccount(broker_id="B宝城期货", account_id="882001598", password="Cxc105153"), web_gui="http://0.0.0.0:8081")
# 主动合约
zd_symbol = "SHFE.ss2010"
zd_quote = api.get_quote(zd_symbol)
zd_position = api.get_position(zd_symbol)

# 被动合约
bd_symbol = "SHFE.ss2011"
bd_quote = api.get_quote(bd_symbol)
bd_position = api.get_position(bd_symbol)

# 初始化可开仓位和可平仓位
pos_total = abs(zd_position.pos)
logger.info("{0}净持仓（总多-总空）：{1}手", zd_symbol, pos_total)
s1.zd_strategy["open_volume"] = s1.zd_strategy["max_volume"] - pos_total
s1.zd_strategy["close_volume"] = min(s1.zd_strategy["max_volume"], pos_total)
logger.info("{0}主动合约策略详情：{1}", zd_symbol, s1.zd_strategy)

while True:
    api.wait_update()
    buy_spread = zd_quote.ask_price1 - bd_quote.bid_price1
    sell_spread = zd_quote.bid_price1 - bd_quote.ask_price1

    # _order_id = _generate_uuid("s1")
    if buy_spread <= s1.zd_open_spread() and s1.zd_open_volume() > 0:
        _volume = min(zd_quote.ask_volume1, bd_quote.bid_volume1, s1.zd_open_volume())
        logger.info("开仓买价差：{0}，主动合约{1}卖一档{2}，{3}；被动合约{4}买一档{5}，{6}；下单量：{7}", buy_spread, bd_symbol, zd_quote.ask_price1, zd_quote.ask_volume1, bd_symbol, bd_quote.bid_price1,
                    bd_quote.bid_volume1, _volume)

        api.insert_order(symbol=zd_symbol, direction="BUY", offset="OPEN", volume=_volume, limit_price=zd_quote.ask_price1)
        api.insert_order(symbol=bd_symbol, direction="SELL", offset="OPEN", volume=_volume, limit_price=bd_quote.bid_price1)

        s1.update_zd_left_volume(_volume, "OPEN")
    elif sell_spread >= s1.zd_close_spread() and s1.zd_close_volume() > 0:
        logger.info("平仓卖价差：{0}", sell_spread)
        logger.info("账户：{0}", api.get_account())

        _volume = min(zd_quote.bid_volume1, bd_quote.ask_volume1, s1.zd_close_volume())

        _pos_long_today = 0
        # 多头今仓大于0且小于下单量
        if 0 < zd_position.pos_long_today <= _volume:
            _pos_long_today = zd_position.pos_long_today
        # 多头今仓大于0且大于下单量
        elif 0 < zd_position.pos_long_today > _volume:
            _pos_long_today = _volume

        if _pos_long_today > 0:
            api.insert_order(symbol=zd_symbol, direction="SELL", offset="CLOSETODAY", volume=_pos_long_today, limit_price=zd_quote.bid_price1)
        if _volume - _pos_long_today > 0:
            # 剩余平老仓
            api.insert_order(symbol=zd_symbol, direction="SELL", offset="CLOSE", volume=_volume - _pos_long_today, limit_price=zd_quote.bid_price1)

        _pos_short_today = 0
        # 空头今仓大于0且小于下单量
        if 0 < bd_position.pos_short_today <= _volume:
            _pos_short_today = bd_position.pos_short_today
        # 空头今仓大于0且大于下单量
        elif 0 < bd_position.pos_short_today > _volume:
            _pos_short_today = _volume

        if _pos_short_today > 0:
            api.insert_order(symbol=bd_symbol, direction="BUY", offset="CLOSETODAY", volume=_pos_short_today, limit_price=bd_quote.ask_price1)
        if _volume - _pos_short_today > 0:
            api.insert_order(symbol=bd_symbol, direction="BUY", offset="CLOSE", volume=_volume - _pos_short_today, limit_price=bd_quote.ask_price1)

        s1.update_zd_left_volume(_volume, "CLOSE")
